package com.uobgroup.ews.uam.core.configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.uobgroup.ews.uam.core.exception.PropertyNotFoundException;

public class AppConfig extends PropertyPlaceholderConfigurer {

   private static Map<String, String> propertiesMap;

   private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK;

   @Override
   public void setSystemPropertiesMode(int systemPropertiesMode) {
      super.setSystemPropertiesMode(systemPropertiesMode);
      springSystemPropertiesMode = systemPropertiesMode;
   }

   @Override
   protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
         throws BeansException {
      super.processProperties(beanFactory, props);

      propertiesMap = new HashMap<String, String>();
      for (Object key : props.keySet()) {
         String keyStr = key.toString();
         String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
         propertiesMap.put(keyStr, valueStr);
      }
   }

   public static String getProperty(String name) {
      return propertiesMap.get(name);
   }
   
   public static void validate(String propertyName) {
       String propertyValue = AppConfig.getProperty(propertyName);
       if (propertyValue == null || propertyValue.trim().length() == 0)
          throw new PropertyNotFoundException("Property " + propertyName + " not found");
    }
}
